<template>
  <div>
    <el-table :data="materials" style="width: 100%">
      <el-table-column prop="name" label="物料名称" width="180"></el-table-column>
      <el-table-column prop="price" label="物料价格" width="180"></el-table-column>
      <el-table-column label="数量" width="180">
        <template v-slot="scope">
          <el-input-number v-model="scope.row.count" :min="1" size="small"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-checkbox v-model="scope.row.selected" :disabled="isOtherMaterialSelected(scope.row)">选择</el-checkbox>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="applySelectedMaterial" type="primary" :disabled="!isMaterialSelected">申请</el-button>
  </div>
</template>

<script setup>
import { ref, onMounted,computed  } from 'vue';
import { ElMessage } from 'element-plus';
import materialApi from '../api/material.js';

const materials = ref([]);
const isMaterialSelected = computed(() => materials.value.some(material => material.selected));

const isOtherMaterialSelected = (material) => {
  return isMaterialSelected.value && !material.selected;
};
const fetchMaterials = async () => {
  try {
    const res = await materialApi.getAllMaterial();
    if (res.data && res.data.code === 200) {
      materials.value = res.data.data.map(material => ({ ...material, selected: false, count: 1 }));
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    ElMessage.error('获取物料数据失败');
  }
};

const applySelectedMaterial = async () => {
  const selectedMaterial = materials.value.find(material => material.selected);
  if (selectedMaterial) {
    try {
      // work_order_id等后续传
      const response = await materialApi.applyMaterials({ id: selectedMaterial.id, count: selectedMaterial.count, work_order_id: "2" });
      if (response.data && response.data.code === 200) {
        ElMessage.success('物料申请成功');
        selectedMaterial.selected = false; // 重置选择状态
      } else {
        ElMessage.error(response.data.message);
      }
    } catch (error) {
      ElMessage.error('物料申请失败');
    }
  }
};

onMounted(() => {
  fetchMaterials();
});
</script>
